package com.example.hello;

import com.vaadin.event.FieldEvents;
import com.vaadin.event.ShortcutAction;
import com.vaadin.ui.AbstractTextField;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class TextField extends com.vaadin.ui.TextField {

    public TextField() {
        this(null);
    }

    public TextField(String caption) {
        setCaption(caption);
        setStyleName("form-control");
    }

    public String getEncodedValue() {
        try {
            return URLEncoder.encode(getValue(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return getValue();
        }
    }

    public static void enterKeyHandler(final BootstrapButton button, final AbstractTextField... fields) {
        for (AbstractTextField field : fields) {
            field.addFocusListener(new FieldEvents.FocusListener() {
                public void focus(final FieldEvents.FocusEvent event) {
                    button.setClickShortcut(ShortcutAction.KeyCode.ENTER);
                }
            });
            field.addBlurListener(new FieldEvents.BlurListener() {
                @Override
                public void blur(final FieldEvents.BlurEvent event) {
                    button.removeClickShortcut();
                }
            });
        }
    }

}